/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * main.java
 *
 * Created on 18.09.2011, 16:20:39
 */
package de.aeo.bll;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.SplashScreen;
import java.awt.Toolkit;
import java.awt.geom.Rectangle2D;
import java.awt.geom.Rectangle2D.Double;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.ListCellRenderer;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;

/**
 * @author Frederic Branczyk & Robert Piwonski
 */
public class main extends javax.swing.JFrame {
    
    //Variables declaration Start
    
    private DefaultListModel studentsListModel;
    private DefaultListModel subjectsListModel;
    private StudentsForm studentsForm;
    private SubjectsForm subjectsForm;
    private ButtonGroup languages;
    private ArrayList<Integer> deniedStudents;
    private JFileChooser chooser;
    private DefaultTableModel dtm;
    private boolean studentsEditable = true;
    private boolean subjectEditable = true;
    private Algorithm a;
    private FindSplitCourseFrame fscf = null;
    private Graphics2D splashGraphics;
    private static SplashScreen mySplash;
    private Double splashTextArea;
    private Double splashProgressArea;
    
    //Variables declaration End

    /** Creates new form main */
    public main(String title) {
        this.setTitle(title);
        this.a = new Algorithm();
        String[] header = {
            this.a.getLanguageString("lastname"),
            this.a.getLanguageString("firstname"),
            this.a.getLanguageString("class"),
            this.a.getLanguageString("subject")+" 1",
            this.a.getLanguageString("subject")+" 2",
            this.a.getLanguageString("subject")+" 3",
            this.a.getLanguageString("subject")+" 4",
            this.a.getLanguageString("subject")+" 5",
            this.a.getLanguageString("subject")+" 6"
        };
        this.dtm = new DefaultTableModel(null, header);
        this.chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter(this.a.getLanguageString("nameExtension"),"csv");
        chooser.setFileFilter(filter);
        this.languages = new ButtonGroup();
        this.studentsForm = new StudentsForm(this.a.getLanguageString("student"), a, this);
        this.subjectsForm = new SubjectsForm(this.a.getLanguageString("subject"), a, this);
        this.studentsListModel = new DefaultListModel();
        this.studentsListModel.addElement("...");
        this.subjectsListModel = new DefaultListModel();
        this.subjectsListModel.addElement("...");
        this.deniedStudents = new ArrayList<Integer>();
        initComponents();
        this.jRadioButtonMenuItemGerman.setSelected(true);
        this.jListStudents.setCellRenderer(new MyListCellRenderer());
        this.jTable1.setAutoCreateRowSorter(true);
        
        this.setLocation(
                this.getX()+(Toolkit.getDefaultToolkit().getScreenSize().width/2)-(this.getWidth()/2), 
                this.getY()+(Toolkit.getDefaultToolkit().getScreenSize().height/2)-(this.getHeight()/2));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMenuBar2 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu4 = new javax.swing.JMenu();
        jScrollPane1 = new javax.swing.JScrollPane();
        jListSubjects = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        jLabelSubjectCount = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        jListStudents = new javax.swing.JList();
        jLabelStudentCount = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jButtonDelete = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenuFile = new javax.swing.JMenu();
        jMenuItemImport = new javax.swing.JMenuItem();
        jMenuItemSave = new javax.swing.JMenuItem();
        jMenuItemClose = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItemCreateCourses = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();
        jMenuLanguage = new javax.swing.JMenu();
        jRadioButtonMenuItemEnglish = new javax.swing.JRadioButtonMenuItem();
        jRadioButtonMenuItemGerman = new javax.swing.JRadioButtonMenuItem();

        jMenu1.setText("File");
        jMenuBar2.add(jMenu1);

        jMenu4.setText("Edit");
        jMenuBar2.add(jMenu4);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        jListSubjects.setModel(this.subjectsListModel);
        jListSubjects.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jListSubjects.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jListSubjectsMouseClicked(evt);
            }
        });
        jListSubjects.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jListSubjectsKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jListSubjectsKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jListSubjectsKeyTyped(evt);
            }
        });
        jScrollPane1.setViewportView(jListSubjects);

        jLabel1.setText(this.a.getLanguageString("amount")+":");

        jLabelSubjectCount.setText("0");

        jTable1.setModel(this.dtm);
        jScrollPane3.setViewportView(jTable1);

        jListStudents.setModel(this.studentsListModel);
        jListStudents.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jListStudents.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jListStudentsMouseClicked(evt);
            }
        });
        jListStudents.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jListStudentsKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jListStudentsKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jListStudentsKeyTyped(evt);
            }
        });
        jScrollPane2.setViewportView(jListStudents);

        jLabelStudentCount.setText("0");

        jLabel4.setText(this.a.getLanguageString("amount")+":");

        jLabel2.setText(this.a.getLanguageString("subjects"));

        jLabel3.setText(this.a.getLanguageString("students"));

        jButtonDelete.setText(this.a.getLanguageString("delete"));
        jButtonDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDeleteActionPerformed(evt);
            }
        });

        jMenuFile.setText(this.a.getLanguageString("file"));
        jMenuFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuFileActionPerformed(evt);
            }
        });

        jMenuItemImport.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItemImport.setText(this.a.getLanguageString("open"));
        jMenuItemImport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemImportActionPerformed(evt);
            }
        });
        jMenuFile.add(jMenuItemImport);

        jMenuItemSave.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItemSave.setText(this.a.getLanguageString("save"));
        jMenuItemSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemSaveActionPerformed(evt);
            }
        });
        jMenuFile.add(jMenuItemSave);

        jMenuItemClose.setText(this.a.getLanguageString("close"));
        jMenuItemClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemCloseActionPerformed(evt);
            }
        });
        jMenuFile.add(jMenuItemClose);

        jMenuBar1.add(jMenuFile);

        jMenu2.setText(this.a.getLanguageString("run"));
        jMenu2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu2ActionPerformed(evt);
            }
        });

        jMenuItemCreateCourses.setText(this.a.getLanguageString("createCourses"));
        jMenuItemCreateCourses.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemCreateCoursesActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItemCreateCourses);

        jMenuBar1.add(jMenu2);

        jMenu3.setText(this.a.getLanguageString("options"));

        jMenuLanguage.setText(this.a.getLanguageString("language"));

        this.languages.add(jRadioButtonMenuItemEnglish);
        jRadioButtonMenuItemEnglish.setText(this.a.getLanguageString("languageEnglish"));
        jRadioButtonMenuItemEnglish.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonMenuItemEnglishActionPerformed(evt);
            }
        });
        jMenuLanguage.add(jRadioButtonMenuItemEnglish);

        this.languages.add(jRadioButtonMenuItemGerman);
        jRadioButtonMenuItemGerman.setText(this.a.getLanguageString("languageGerman"));
        jRadioButtonMenuItemGerman.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonMenuItemGermanActionPerformed(evt);
            }
        });
        jMenuLanguage.add(jRadioButtonMenuItemGerman);

        jMenu3.add(jMenuLanguage);

        jMenuBar1.add(jMenu3);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 882, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabelSubjectCount))
                            .addComponent(jLabel2)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 431, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabelStudentCount)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 256, Short.MAX_VALUE)
                                .addComponent(jButtonDelete))
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 433, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButtonDelete)
                            .addComponent(jLabel4)
                            .addComponent(jLabelStudentCount)
                            .addComponent(jLabel1)
                            .addComponent(jLabelSubjectCount))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 318, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jListSubjectsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListSubjectsMouseClicked
        if (evt.getClickCount() == 2)
            this.editSubject();
    }//GEN-LAST:event_jListSubjectsMouseClicked

    private void jListStudentsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListStudentsMouseClicked
        if (evt.getClickCount() == 2)
            this.editStudent();
    }//GEN-LAST:event_jListStudentsMouseClicked

    private void jMenuItemSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemSaveActionPerformed
        try {
            this.setFocusable(false);
            int returnVal = chooser.showSaveDialog(this);
            if(returnVal == JFileChooser.APPROVE_OPTION) {
                boolean fileExists = chooser.getSelectedFile().exists();
                while(fileExists) {
                    int result = JOptionPane.showConfirmDialog(this, this.a.getLanguageString("overrideMsg"), this.a.getLanguageString("titleWarning"), 0);
                    if(result==0) {
                        fileExists = false;
                        break;
                    }else if(result==-1){
                        return;
                    }else {
                        chooser.showSaveDialog(this);
                        fileExists = chooser.getSelectedFile().exists();
                    }
                }
                this.a.exportData(chooser.getSelectedFile());
            }
            this.setFocusable(true);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), this.a.getLanguageString("titleWarning"), 0);
        }
    }//GEN-LAST:event_jMenuItemSaveActionPerformed

    private void jMenuItemCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemCloseActionPerformed
        if(JOptionPane.showConfirmDialog(this, this.a.getLanguageString("exitMsg"), this.a.getLanguageString("titleWarning"), 0, 2)==0) {
            this.setVisible(false);
            System.exit(0);
        }
    }//GEN-LAST:event_jMenuItemCloseActionPerformed

    private void jMenuItemImportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemImportActionPerformed
        try {
            this.setFocusable(false);
            int returnVal = chooser.showOpenDialog(this);
            if(returnVal == JFileChooser.APPROVE_OPTION) {
                this.a.importData(chooser.getSelectedFile());
                this.refreshSubjectList();
                this.refreshStudentList();
                this.createPreview();
            }
            this.setFocusable(true);
        }catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), this.a.getLanguageString("titleWarning"), 0);
        }
    }//GEN-LAST:event_jMenuItemImportActionPerformed

    private void jMenuFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuFileActionPerformed
        // deprecated
    }//GEN-LAST:event_jMenuFileActionPerformed

    private void jListSubjectsKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jListSubjectsKeyReleased
        // deprecated
    }//GEN-LAST:event_jListSubjectsKeyReleased

    private void jListStudentsKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jListStudentsKeyReleased
        // deprecated
    }//GEN-LAST:event_jListStudentsKeyReleased

    private void jRadioButtonMenuItemEnglishActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItemEnglishActionPerformed
        this.setLanguage();
    }//GEN-LAST:event_jRadioButtonMenuItemEnglishActionPerformed

    private void jRadioButtonMenuItemGermanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItemGermanActionPerformed
        this.setLanguage();
    }//GEN-LAST:event_jRadioButtonMenuItemGermanActionPerformed

    private void jButtonDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDeleteActionPerformed
        int index = this.jListStudents.getSelectedIndex();
        if(index!=-1 && index!=this.a.getStudentCount()) {
            if(JOptionPane.showConfirmDialog(this, this.a.getLanguageString("sureDeleteMsg")+"\n\n- \""+this.jListStudents.getModel().getElementAt(index)+"\"", this.a.getLanguageString("titleWarning"), 0)==0) {
                this.a.getStudentList().remove(index);
                DefaultListModel dlm = (DefaultListModel) this.jListStudents.getModel();
                dlm.remove(index);
                this.createPreview();
                this.jLabelStudentCount.setText(Integer.toString(Integer.parseInt(this.jLabelStudentCount.getText())-1));
            }
        }else {
            JOptionPane.showMessageDialog(this, this.a.getLanguageString("noDeleteIndexMsg"), this.a.getLanguageString("titleWarning"), 0);
        }
    }//GEN-LAST:event_jButtonDeleteActionPerformed

    private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu2ActionPerformed
        //deprecated
    }//GEN-LAST:event_jMenu2ActionPerformed

    private void jListSubjectsKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jListSubjectsKeyTyped
        // deprecated
    }//GEN-LAST:event_jListSubjectsKeyTyped

    private void jListStudentsKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jListStudentsKeyPressed
        if(evt.getKeyCode()==10 && this.isFocused())
            this.editStudent();
    }//GEN-LAST:event_jListStudentsKeyPressed

    private void jListStudentsKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jListStudentsKeyTyped
        // depreacted
    }//GEN-LAST:event_jListStudentsKeyTyped

    private void jListSubjectsKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jListSubjectsKeyPressed
        if(evt.getKeyCode()==10 && this.isFocused())
            this.editSubject();
    }//GEN-LAST:event_jListSubjectsKeyPressed

    private void jMenuItemCreateCoursesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemCreateCoursesActionPerformed
        this.a.createInitialCourseList();
        if(this.fscf==null) {
            this.fscf = new FindSplitCourseFrame(this.a);
        }else{
            this.fscf.updateObject();
        }
        this.fscf.setLocation(
                this.getX()+(this.getWidth()/2)-(this.fscf.getWidth()/2), 
                this.getY()+(this.getHeight()/2)-(this.fscf.getHeight()/2));
        this.setVisible(false);
        this.fscf.setVisible(true);
    }//GEN-LAST:event_jMenuItemCreateCoursesActionPerformed
    
    public JLabel getJLabelSubjectCount() {
        return this.jLabelSubjectCount;
    }
    
    public JLabel getJLabelStudentCount() {
        return this.jLabelStudentCount;
    }

    public boolean isStudentsEditable() {
        return studentsEditable;
    }

    public void setStudentsEditable(boolean studentsEditable) {
        this.studentsEditable = studentsEditable;
    }

    public boolean isSubjectEditable() {
        return subjectEditable;
    }

    public void setSubjectEditable(boolean subjectEditable) {
        this.subjectEditable = subjectEditable;
    }
    
    public void editSubject() {
        Subject s;
        int subjectIndex;
//        System.out.println("---");
//        System.out.println("SelectedIndex: "+this.jListStudents.getSelectedIndex());
//        System.out.println("SubjectCount: "+this.m.getSubjectCount());
        if(this.jListSubjects.getSelectedIndex()==this.a.getSubjectCount()) {
//            System.out.println("SelectedIndex==SubjectCount");
            s = null;
            subjectIndex = -1;
        }else {
//            System.out.println("SelectedIndex!=SubjectCount");
            s = this.a.getSubjectList().get(this.jListSubjects.getSelectedIndex());
            subjectIndex = this.jListSubjects.getSelectedIndex();
            this.subjectsForm.getjTextFieldName().setText(s.getName());
            this.subjectsForm.getjTextFieldAbbreviation().setText(s.getAbbreviation());
            this.subjectsForm.getjComboBoxMinStudents().setSelectedIndex(s.getMinStudents()-this.a.getSubjectMinMin());
            this.subjectsForm.getjComboBoxMaxStudents().setSelectedIndex(s.getMaxStudents()-this.a.getSubjectMaxMin());
            this.subjectsForm.getjComboBoxPeriod().setSelectedIndex(s.getPeriod()-1);
        }
        this.subjectsForm.setEditSubject(s);
        if(s!=null) {
//            System.out.println("EditSubject: "+s.getName()+" - "+s.getAbbreviation());
        }else {
//            System.out.println("EditSubject: null");
        }
        this.subjectsForm.setEditSubjectIndex(subjectIndex);
//        System.out.println("subjectIndex: "+subjectIndex);
        this.subjectsForm.setLocation(
                this.getX()+(this.getWidth()/2)-(this.subjectsForm.getWidth()/2), 
                this.getY()+(this.getHeight()/2)-(this.subjectsForm.getHeight()/2));
        this.subjectsForm.getjTextFieldName().requestFocusInWindow();
        this.subjectsForm.setVisible(true);
        this.setFocusable(false);
        this.subjectEditable = false;
    }
    
    public void refreshSubjectList() {
        ArrayList<Subject> list = this.a.getSubjectList();
        DefaultListModel model = new DefaultListModel();
        for(Subject s:list) {
            model.add(model.size(), s);
        }
        model.add(model.size(), "...");
        this.jListSubjects.setModel(model);
        this.jLabelSubjectCount.setText(Integer.toString(this.a.getSubjectList().size()));
//        System.out.println("Subject Size: "+this.m.getSubjectList().size());
    }
    
    public void editStudent() {
        DefaultComboBoxModel cbm1 = (DefaultComboBoxModel) this.studentsForm.getjComboBoxSubject1().getModel();
        cbm1.removeAllElements();
        cbm1.addElement(this.a.getLanguageString("<none>"));
        for(Subject s1:this.a.getSubjectList()) {
            cbm1.addElement(s1);
        }
        DefaultComboBoxModel cbm2 = (DefaultComboBoxModel) this.studentsForm.getjComboBoxSubject2().getModel();
        cbm2.removeAllElements();
        cbm2.addElement(this.a.getLanguageString("<none>"));
        for(Subject s2:this.a.getSubjectList()) {
            cbm2.addElement(s2);
        }
        DefaultComboBoxModel cbm3 = (DefaultComboBoxModel) this.studentsForm.getjComboBoxSubject3().getModel();
        cbm3.removeAllElements();
        cbm3.addElement(this.a.getLanguageString("<none>"));
        for(Subject s3:this.a.getSubjectList()) {
            cbm3.addElement(s3);
        }
        DefaultComboBoxModel cbm4 = (DefaultComboBoxModel) this.studentsForm.getjComboBoxSubject4().getModel();
        cbm4.removeAllElements();
        cbm4.addElement(this.a.getLanguageString("<none>"));
        for(Subject s4:this.a.getSubjectList()) {
            cbm4.addElement(s4);
        }
        DefaultComboBoxModel cbm5 = (DefaultComboBoxModel) this.studentsForm.getjComboBoxSubject5().getModel();
        cbm5.removeAllElements();
        cbm5.addElement(this.a.getLanguageString("<none>"));
        for(Subject s5:this.a.getSubjectList()) {
            cbm5.addElement(s5);
        }
        DefaultComboBoxModel cbm6 = (DefaultComboBoxModel) this.studentsForm.getjComboBoxSubject6().getModel();
        cbm6.removeAllElements();
        cbm6.addElement(this.a.getLanguageString("<none>"));
        for(Subject s6:this.a.getSubjectList()) {
            cbm6.addElement(s6);
        }
        Student s;
        int studentIndex;
//        System.out.println("---");
//        System.out.println("SelectedIndex: "+this.jListStudents.getSelectedIndex());
//        System.out.println("StudentCount: "+this.m.getStudentCount());
        if(this.a.getSubjectList().isEmpty()) {
            try {
                throw new NoSubjectsException(this.a.getLanguageString("noSubjectsCreated"));
            }catch(Exception ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage());
                return;
            }
        }else if(this.jListStudents.getSelectedIndex()==this.a.getStudentCount()) {
//            System.out.println("SelectedIndex==StudentCount");
            s = null;
            studentIndex = -1;
        }else{
//            System.out.println("SelectedIndex!=StudentCount");
            s = this.a.getStudentList().get(this.jListStudents.getSelectedIndex());
            studentIndex = this.jListStudents.getSelectedIndex();
            this.studentsForm.getjTextFieldFirstname().setText(s.getFirstname());
            this.studentsForm.getjTextFieldLastname().setText(s.getLastname());
            this.studentsForm.getjComboBoxClass().setSelectedItem(s.getcClass());
            System.out.println(this.a.getSubjectList().indexOf(s.getSubjectList()[0])+1);
            this.studentsForm.getjComboBoxSubject1().setSelectedIndex(this.a.getSubjectList().indexOf(s.getSubjectList()[0])+1);
            System.out.println(this.a.getSubjectList().indexOf(s.getSubjectList()[1])+1);
            this.studentsForm.getjComboBoxSubject2().setSelectedIndex(this.a.getSubjectList().indexOf(s.getSubjectList()[1])+1);
            System.out.println(this.a.getSubjectList().indexOf(s.getSubjectList()[2])+1);
            this.studentsForm.getjComboBoxSubject3().setSelectedIndex(this.a.getSubjectList().indexOf(s.getSubjectList()[2])+1);
            System.out.println(this.a.getSubjectList().indexOf(s.getSubjectList()[3])+1);
            this.studentsForm.getjComboBoxSubject4().setSelectedIndex(this.a.getSubjectList().indexOf(s.getSubjectList()[3])+1);
            System.out.println(this.a.getSubjectList().indexOf(s.getSubjectList()[4])+1);
            this.studentsForm.getjComboBoxSubject5().setSelectedIndex(this.a.getSubjectList().indexOf(s.getSubjectList()[4])+1);
            System.out.println(this.a.getSubjectList().indexOf(s.getSubjectList()[5])+1);
            this.studentsForm.getjComboBoxSubject6().setSelectedIndex(this.a.getSubjectList().indexOf(s.getSubjectList()[5])+1);
        }
        this.studentsForm.setEditStudent(s);
//        if(s!=null) {
//            System.out.println("EditStudent: "+s.getFirstname()+" "+s.getLastname()+" - "+s.getcClass());
//            System.out.println("Chosen Subjects: "+Arrays.toString(s.getSubjectList()));
//        }else {
//            System.out.println("EditStudent: null");
//        }
        this.studentsForm.setEditStudentIndex(studentIndex);
//        System.out.println("subjectIndex: "+studentIndex);
        this.studentsForm.setLocation(
                this.getX()+(this.getWidth()/2)-(this.studentsForm.getWidth()/2), 
                this.getY()+(this.getHeight()/2)-(this.studentsForm.getHeight()/2));
        this.studentsForm.getjTextFieldFirstname().requestFocusInWindow();
        this.studentsForm.setVisible(true);
        this.setFocusable(false);
        this.studentsEditable = false;
    }
    
    public void refreshStudentList() {
        ArrayList<Student> list = this.a.getStudentList();
        DefaultListModel model = new DefaultListModel();
        for(Student s:list) {
            model.add(model.size(), s);
        }
        model.add(model.size(), "...");
        this.jLabelStudentCount.setText(Integer.toString(this.a.getStudentList().size()));
        this.jListStudents.setModel(model);
        System.out.println("Student Size: "+this.a.getStudentList().size());
    }

    public JList getjListStudents() {
        return jListStudents;
    }

    public JList getjListSubjects() {
        return jListSubjects;
    }
    
    public void setLanguage() {
        if(this.jRadioButtonMenuItemEnglish.isSelected()) {
            this.a.setLanguage(new Language_en());
            this.reloadLanguageData();
        }else if(this.jRadioButtonMenuItemGerman.isSelected()){
            this.a.setLanguage(new Language_de());
            this.reloadLanguageData();
        }
    }
    
    public void createPreview() {
        ArrayList<Student> list = new ArrayList<Student>(this.a.getStudentList());
        Collections.sort(list);
        int i = 0;
        String[][] data = new String[list.size()][9];
        for(Student s:list) {
            String[] str = {null, null, null, null, null, null, null, null, null};
            str[0] = s.getLastname();
            str[1] = s.getFirstname();
            str[2] = s.getcClass();
            if(s.getSubjectList()[0]!=null)
                str[3] = s.getSubjectList()[0].getAbbreviation()+s.getSubjectList()[0].getPeriodAbbreviation();
            else
                str[3] = this.a.getLanguageString("<none>");
            if(s.getSubjectList()[1]!=null)
                str[4] = s.getSubjectList()[1].getAbbreviation()+s.getSubjectList()[1].getPeriodAbbreviation();
            else
                str[4] = this.a.getLanguageString("<none>");
            if(s.getSubjectList()[2]!=null)
                str[5] = s.getSubjectList()[2].getAbbreviation()+s.getSubjectList()[2].getPeriodAbbreviation();
            else
                str[5] = this.a.getLanguageString("<none>");
            if(s.getSubjectList()[3]!=null)
                str[6] = s.getSubjectList()[3].getAbbreviation()+s.getSubjectList()[3].getPeriodAbbreviation();
            else
                str[6] = this.a.getLanguageString("<none>");
            if(s.getSubjectList()[4]!=null)
                str[7] = s.getSubjectList()[4].getAbbreviation()+s.getSubjectList()[4].getPeriodAbbreviation();
            else
                str[7] = this.a.getLanguageString("<none>");
            if(s.getSubjectList()[5]!=null)
                str[8] = s.getSubjectList()[5].getAbbreviation()+s.getSubjectList()[5].getPeriodAbbreviation();
            else
                str[8] = this.a.getLanguageString("<none>");
            data[i] = str;
            i++;
        }
        
        String[] header = {
            this.a.getLanguageString("lastname"),
            this.a.getLanguageString("firstname"),
            this.a.getLanguageString("class"),
            this.a.getLanguageString("subject")+" 1",
            this.a.getLanguageString("subject")+" 2",
            this.a.getLanguageString("subject")+" 3",
            this.a.getLanguageString("subject")+" 4",
            this.a.getLanguageString("subject")+" 5",
            this.a.getLanguageString("subject")+" 6"
        };
        
        DefaultTableModel dtm1 = new DefaultTableModel(data, header){
            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return false;
            }
        };
        
        this.jTable1.setModel(dtm1);
        
        this.check();
    }
    
    public void check() {
        this.deniedStudents = this.a.timeCheck();
        if(!this.deniedStudents.isEmpty())
            this.jListStudents.repaint();
    }
    
    private void reloadLanguageData() {
        this.jLabel4.setText(this.a.getLanguageString("amount")+":");
        this.jLabel1.setText(this.a.getLanguageString("amount")+":");
        this.jLabel3.setText(this.a.getLanguageString("students"));
        this.jLabel2.setText(this.a.getLanguageString("subjects"));
        this.jMenu3.setText(this.a.getLanguageString("options"));
        this.jMenuLanguage.setText(this.a.getLanguageString("language"));
        this.jRadioButtonMenuItemEnglish.setText(this.a.getLanguageString("languageEnglish"));
        this.jRadioButtonMenuItemGerman.setText(this.a.getLanguageString("languageGerman"));
        this.jMenu2.setText(this.a.getLanguageString("run"));
        this.jMenuFile.setText(this.a.getLanguageString("file"));
        this.jMenuItemSave.setText(this.a.getLanguageString("save"));
        this.jMenuItemImport.setText(this.a.getLanguageString("open"));
        this.jMenuItemClose.setText(this.a.getLanguageString("close"));
        this.studentsForm.reloadLanguageData();
        this.subjectsForm.reloadLanguageData();
        this.setTitle(this.a.getLanguageString("programTitle"));
        this.jButtonDelete.setText(this.a.getLanguageString("delete"));
        this.jMenuItemCreateCourses.setText(this.a.getLanguageString("createCourses"));
        String[] header = {
            this.a.getLanguageString("lastname"),
            this.a.getLanguageString("firstname"),
            this.a.getLanguageString("class"),
            this.a.getLanguageString("subject")+" 1",
            this.a.getLanguageString("subject")+" 2",
            this.a.getLanguageString("subject")+" 3",
            this.a.getLanguageString("subject")+" 4",
            this.a.getLanguageString("subject")+" 5",
            this.a.getLanguageString("subject")+" 6"
        };
        DefaultTableModel dtm1 = (DefaultTableModel) this.jTable1.getModel();
        dtm1.setColumnIdentifiers(header);
        this.createPreview();
    }
    
    /**
     * Prepare the global variables for the other splash functions
     */
    private void splashInit() throws NullPointerException, IOException
    {
        mySplash = SplashScreen.getSplashScreen();
        if (mySplash != null)
        {   // if there are any problems displaying the splash this will be null
            Dimension ssDim = mySplash.getSize();
            int height = ssDim.height;
            int width = ssDim.width;
            // stake out some area for our status information
            splashTextArea = new Rectangle2D.Double(15., height*0.88, width * .45, 32.);
            splashProgressArea = new Rectangle2D.Double(width * .55, height*.92, width*.4, 12 );
            // create the Graphics environment for drawing status info
            splashGraphics = mySplash.createGraphics();
//            font = new Font("Dialog", Font.PLAIN, 14);
//            splashGraphics.setFont(font);
            
            // initialize the status info
            splashText("Starting");
            splashProgress(0);
        }
    }
    
    /**
     * Display text in status area of Splash.  Note: no validation it will fit.
     * @param str - text to be displayed
     */
    public void splashText(String str)
    {
        if (mySplash != null && mySplash.isVisible())
        {   // important to check here so no other methods need to know if there
            // really is a Splash being displayed

            // erase the last status text
            splashGraphics.setPaint(Color.LIGHT_GRAY);
            splashGraphics.fill(splashTextArea);

            // draw the text
            splashGraphics.setPaint(Color.BLACK);
            splashGraphics.drawString(str, (int)(splashTextArea.getX() + 10),(int)(splashTextArea.getY() + 15));

            // make sure it's displayed
            mySplash.update();
        }
    }
    
    /**
     * Display a (very) basic progress bar
     * @param pct how much of the progress bar to display 0-100
     */
    public void splashProgress(int pct)
    {
        if (mySplash != null && mySplash.isVisible())
        {

            // Note: 3 colors are used here to demonstrate steps
            // erase the old one
            splashGraphics.setPaint(Color.LIGHT_GRAY);
            splashGraphics.fill(splashProgressArea);

            // draw an outline
            splashGraphics.setPaint(Color.BLUE);
            splashGraphics.draw(splashProgressArea);

            // Calculate the width corresponding to the correct percentage
            int x = (int) splashProgressArea.getMinX();
            int y = (int) splashProgressArea.getMinY();
            int wid = (int) splashProgressArea.getWidth();
            int hgt = (int) splashProgressArea.getHeight();

            int doneWidth = Math.round(pct*wid/100.f);
            doneWidth = Math.max(0, Math.min(doneWidth, wid-1));  // limit 0-width

            // fill the done part one pixel smaller than the outline
            splashGraphics.setPaint(Color.GREEN);
            splashGraphics.fillRect(x, y+1, doneWidth, hgt-1);

            // make sure it's displayed
            mySplash.update();
        }
    }

    /**
     * just a stub to simulate a long initialization task that updates
     * the text and progress parts of the status in the Splash
     */

    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        main m = new main("Course Courser");
        try {
            m.splashInit();
        } catch (NullPointerException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        }
        if( mySplash != null ) {
            try { Thread.currentThread().sleep(3000L); }
            catch ( Exception e ) { }
            mySplash.close();
        }
        m.setVisible(true);
    }
    
    class MyListCellRenderer extends JLabel implements ListCellRenderer {
        private final Border SAFE_NO_FOCUS_BORDER = new EmptyBorder(1, 1, 1, 1);
        private final Border DEFAULT_NO_FOCUS_BORDER = new EmptyBorder(1, 1, 1, 1);
        protected Border noFocusBorder = DEFAULT_NO_FOCUS_BORDER;
        
        public MyListCellRenderer() {
            super();
            setOpaque(true);
            setBorder(getNoFocusBorder());
        }
        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            setComponentOrientation(list.getComponentOrientation());

            Color bg = null;
            Color fg = null;

            JList.DropLocation dropLocation = list.getDropLocation();
            if (dropLocation != null
                    && !dropLocation.isInsert()
                    && dropLocation.getIndex() == index) {

                bg = DefaultLookup.getColor(this, ui, "List.dropCellBackground");
                fg = DefaultLookup.getColor(this, ui, "List.dropCellForeground");

                isSelected = true;
            }
            setText(value.toString());
            
            if(isSelected) {
                setBackground(bg == null ? list.getSelectionBackground() : bg);
                setForeground(fg == null ? list.getSelectionForeground() : fg);
            }else if (deniedStudents.contains(index))
                setBackground(new Color(255, 153, 173));
            else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }
            
            setEnabled(list.isEnabled());
            setFont(list.getFont());
            
            Border border = null;
            if (cellHasFocus) {
                if (isSelected) {
                    border = DefaultLookup.getBorder(this, ui, "List.focusSelectedCellHighlightBorder");
                }
                if (border == null) {
                    border = DefaultLookup.getBorder(this, ui, "List.focusCellHighlightBorder");
                }
            } else {
                border = getNoFocusBorder();
            }
            setBorder(border);
            
            return this;
        }

        private Border getNoFocusBorder() {
            Border border = DefaultLookup.getBorder(this, ui, "List.cellNoFocusBorder");
            if (System.getSecurityManager() != null) {
                if (border != null) return border;
                return SAFE_NO_FOCUS_BORDER;
            } else {
                if (border != null &&
                        (noFocusBorder == null ||
                        noFocusBorder == DEFAULT_NO_FOCUS_BORDER)) {
                    return border;
                }
                return noFocusBorder;
            }
        }
    }

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonDelete;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabelStudentCount;
    private javax.swing.JLabel jLabelSubjectCount;
    private javax.swing.JList jListStudents;
    private javax.swing.JList jListSubjects;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu4;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuBar jMenuBar2;
    private javax.swing.JMenu jMenuFile;
    private javax.swing.JMenuItem jMenuItemClose;
    private javax.swing.JMenuItem jMenuItemCreateCourses;
    private javax.swing.JMenuItem jMenuItemImport;
    private javax.swing.JMenuItem jMenuItemSave;
    private javax.swing.JMenu jMenuLanguage;
    private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItemEnglish;
    private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItemGerman;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
